package com.shixi.shixitraining.shixitraining.http;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 * 对请求结果做简单过滤
 */

public abstract class CallbackImple<T> implements Callback<T> {

    /**
     * 简单过滤父类的请求结果
     * @param call
     * @param response
     */
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if(response!=null){
            if(response.isSuccessful()&&response.body()!=null){
                onSuccess(call,response.body());
            }else{
                if(response.errorBody()!=null){
                    try {
                        String msg = response.errorBody().string();
                        Throwable throwable = new Throwable(msg);
                        onError(call,throwable);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Throwable throwable = new Throwable("response errorBody read stream IOException ");
                        onError(call,throwable);
                    }
                }else{
                    Throwable throwable = new Throwable("response errorBody is null");
                    onError(call,throwable);
                }
            }
        }else{
            Throwable throwable = new Throwable("response is null");
            onError(call,throwable);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        onError(call,t);
    }

    public abstract void onError(Call<T> call, Throwable t);
    public abstract void onSuccess(Call<T> call, T response);
}
